package org.dromara.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.ITeachClassService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.run.service.IDeptService;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysDeptImportVo;
import org.dromara.system.domain.vo.SysDeptVo;
import org.dromara.system.service.ISysDeptService;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class SysDeptImportListener extends AnalysisEventListener<SysDeptImportVo> implements ExcelListener<SysDeptImportVo> {

    private final ISysDeptService sysDeptService;
    private final IDeptService deptService;
    private final ITeachClassService teachClassService;

    private final Boolean isUpdateSupport;

    private final Long operUserId;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public SysDeptImportListener(Boolean isUpdateSupport) {
        this.teachClassService=SpringUtils.getBean(ITeachClassService.class);
        this.sysDeptService = SpringUtils.getBean(ISysDeptService.class);
        this.deptService = SpringUtils.getBean(IDeptService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operUserId = LoginHelper.getUserId();
    }

    @Override
    public void invoke(SysDeptImportVo deptImportVo, AnalysisContext context) {
        String parentId = this.deptService.selectDeptIdByDeptName(deptImportVo.getParentName());

        try {
            if(StringUtils.isNotEmpty(parentId)){
                SysDeptVo deptVo = this.sysDeptService.selectDeptVoByDeptNameAndParentId(deptImportVo.getDeptName(),Long.parseLong(parentId));
                if(ObjectUtil.isNull(deptVo)){
                    SysDeptBo deptBo=BeanUtil.toBean(deptImportVo, SysDeptBo.class);
                    deptBo.setParentId(Long.parseLong(parentId));
                    this.sysDeptService.insertDept(deptBo);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、组织结构 ").append(deptBo.getDeptName()).append(" 导入成功");
                }else if(isUpdateSupport){
                    SysDeptBo deptBo=BeanUtil.toBean(deptImportVo, SysDeptBo.class);
                    deptBo.setParentId(Long.parseLong(parentId));
                    this.sysDeptService.updateDept(deptBo);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、组织结构 ").append(deptBo.getDeptName()).append(" 更新成功");

                }else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、组织结构 ").append(deptVo.getDeptName()).append(" 已存在");
                }

            }else {
                failureMsg.append("<br/>").append(deptImportVo.getParentName()).append("该信息的上一级不存在");
            }

        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、数据"  + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<SysDeptImportVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，组织结构信息导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，组织结构信息已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<SysDeptImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
